package com.yike.user.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.lkl.laop.sdk.LKLSDK;
import com.yike.common.base.BaseController;
import com.yike.common.entity.LklArea;
import com.yike.common.enums.OperationLogType;
import com.yike.common.log.OperationLog;
import com.yike.common.tool.StringUtil;
import com.yike.user.lkl.BaseCommon;
import com.yike.user.lkl.incoming.IncomingApi;
import com.yike.user.lkl.incoming.RsaDecrypt;
import com.yike.user.lkl.incoming.push.MerchantAudit;
import com.yike.user.lkl.incoming.push.MerchantModification;
import com.yike.user.lkl.incoming.request.IncomingPush;
import com.yike.user.mapper.LklAreaMapper;
import com.yike.user.service.PlatformShopService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/lkl/notice")
public class NoticeShopController extends BaseController {

    @Autowired
    private PlatformShopService platformShopService;


    @Autowired
    private IncomingApi incomingApi;

    @Autowired
    private LklAreaMapper lklAreaMapper;
    /**
     * 拉卡拉进件推送
     * @param data
     * @return
     */
    @ApiOperation(value = "导入lkl地址信息")
    @PostMapping("importSupplier")
    public String  importSupplier(@RequestParam Integer type) throws IOException {
        if(type.equals(1)){
           List<Map<String,Object>> list = incomingApi.getAreaInfo("1");
           for (Map<String,Object> map : list) {
               String name = map.get("name").toString().replaceAll("\\s+", "");

               LklArea lklArea = new LklArea();
               lklArea.setName(name);
               lklArea.setCode(map.get("code").toString());
               lklArea.setParentCode(map.get("parentCode").toString());
               lklAreaMapper.insert(lklArea);
           }
        }
        if(type.equals(2) || type.equals(3)){
            List<LklArea> list = new ArrayList<>();
            if (type.equals(2)){
                list =  lklAreaMapper.selectList( new LambdaQueryWrapper<LklArea>().eq(LklArea::getParentCode,"1"));

            }else {
                list =  lklAreaMapper.selectList( new LambdaQueryWrapper<LklArea>().ge(LklArea::getParentCode,"1"));
            }
            for (LklArea lklArea : list) {
                List<Map<String,Object>> list1 = incomingApi.getAreaInfo(lklArea.getCode());
                for (Map<String,Object> map : list1) {
                    String name = map.get("name").toString().replaceAll("\\s+", "");
                    LklArea lklAreaInfo = lklAreaMapper.queryName(name);
                    if (lklAreaInfo == null) {
                        LklArea lklArea1 = new LklArea();
                        lklArea1.setName(name);
                        lklArea1.setCode(map.get("code").toString());
                        lklArea1.setParentCode(map.get("parentCode").toString());
                        lklAreaMapper.insert(lklArea1);
                    }

                }
            }
        }

        return null;


    }



    @PostMapping("/merchantPost")
    public Map<String ,Object> merchantPost(@Validated @RequestBody IncomingPush data) {
        log.info("拉卡拉进件推送信息：{}", JSON.toJSONString(data));
        Map<String ,Object> map = new HashMap<>();
        try {
            MerchantAudit merchantAudit = RsaDecrypt.decrypt(data.getData(), MerchantAudit.class);
            if(ObjectUtils.isEmpty(merchantAudit)){
                map.put("code", "500");
                map.put("message", "失败");
                return map;
            }
            platformShopService.updateLklShop(merchantAudit);
            map.put("code", "200");
            map.put("message", "成功");
            return map;
        } catch (Exception e) {
            log.error("拉卡拉推送信息-解密失败：{}", e.getMessage());
            map.put("code", "500");
            map.put("message", "失败");
            return map;
        }
    }

    /**
     * 拉卡拉改件推送
     * @param data
     * @return
     */
    @PostMapping("/merchantUpdatePost")
    public Map<String ,Object> merchantUpdate(@Validated @RequestBody IncomingPush data) {
        log.info("拉卡拉进改件推送信息：{}", JSON.toJSONString(data));
        Map<String ,Object> map = new HashMap<>();
        try {
            MerchantModification merchantModification = RsaDecrypt.decrypt(data.getData(), MerchantModification.class);
            if(ObjectUtils.isEmpty(merchantModification)){
                map.put("code", "500");
                map.put("message", "失败");
                return map;
            }
            platformShopService.updateLklShopUp(merchantModification);
            map.put("code", "200");
            map.put("message", "成功");
            return map;
        } catch (Exception e) {
            log.error("拉卡拉推送信息-解密失败：{}", e.getMessage());
            map.put("code", "500");
            map.put("message", "失败");
            return map;
        }
    }



    /**
     * 拉卡拉申请分账回调
     *
     * @return
     */
    @PostMapping("/applyLedgerMer")
    @OperationLog(name = "拉卡拉申请分账回调", type = OperationLogType.ADD)
    public Map<String ,Object> applyLedgerMerNot(HttpServletRequest request) throws Exception {
        //String body = "{\"payOrderNo\":\"21090611012001970631000463034\",\"merchan tOrderNo\":\"CH2021090613190866292\",\"orderInfo\":null,\"merchantNo\":\"822126090640003\",\"termId\":\"47781282\",\"tradeMerchantNo\":\"822126090640003\",\"tradeTermId\":\"47781282\",\"channelId\":\"10000038\",\"currency\":\"156\",\"amount\":1,\"tradeType\":\"PAY\",\"payStatus\":\"S\",\"notifyStatus\":0,\"orderCreateTime\":\"2021-09-06T05:19:43.000+00:00\",\"orderEfficientTime\":\"2021-09-06T05:19:43.000+00:00\",\"extendField\":null,\"payTime\":\"2021-09-06T05:19:43.000+00:00\",\"remark\":\"\",\"noticeNum\":1,\"sign\":null,\"notifyUrl\":null,\"notifyMode\":\"2\",\"payInfo\":\"1#1#ALIPAY#0#2021090622001432581427657317\",\"lklOrderNo\":\"2021090666210003610012\",\"crdFlg\":\"92\",\"payerId1\":\"2088702852632582\",\"payerId2\":\"rob***@126.com\",\"smCrdFlg\":\"01\",\"tradeTime\":\"20210906131943\",\"accountChannelOrderNo\":\"2021090622001432581427657317\",\"actualPayAmount\":1,\"logNo\":\"66210003610012\"}";
        //String body = LKLSDK.notificationHandle(request);

        //验签
        String body = LKLSDK.notificationHandle(request);

        if (StringUtil.isEmpty(body)) {
            throw new Exception("验签失败");
        }
        log.info("拉卡拉申请分账回调信息：body:{}", body);


        log.info("拉卡拉分账更改回调信息-验签成功");

        return platformShopService.applyLedgerMerNot(body);

    }

    /**
     * 拉卡拉分账更改回调
     *
     * @return
     */
    @PostMapping("/applyLedgerMerUpdate")
    @OperationLog(name = "拉卡拉分账更改回调", type = OperationLogType.ADD)
    public Map<String ,Object> applyLedgerMerUpdate(HttpServletRequest request) throws Exception {
        //验签
        log.info("拉卡拉分账更改回调信息-request");

        String body = LKLSDK.notificationHandle(request);

        if (StringUtil.isEmpty(body)) {
            throw new Exception("验签失败");
        }

        log.info("拉卡拉分账更改回调信息-验签成功");


        return platformShopService.applyLedgerMerUpdateNot(body);
    }


    /**
     * 拉卡拉申请分账绑定接收方回调
     *
     * @return
     */
    @PostMapping("/applyBindNot")
    @OperationLog(name = "拉卡拉申请分账绑定接收方回调", type = OperationLogType.ADD)
    public Map<String ,Object> applyBindNot(HttpServletRequest request) throws Exception {
        //验签
        log.info("拉卡拉申请分账回调信息");
        String body = LKLSDK.notificationHandle(request);

        if (StringUtil.isEmpty(body)) {
            throw new Exception("验签失败");
        }
        log.info("拉卡拉分账更改回调信息-验签成功");

        return platformShopService.applyBindNot(body);

    }
}
